package com.balabala.gym_system.interceptor;

import cn.hutool.jwt.JWT;
import com.balabala.gym_system.config.AdminThreadLocal;
import com.balabala.gym_system.pojo.entity.Admin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Author:zl
 * Date:2023/5/1 13:31
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    //处理器执行之前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.debug("认证拦截器被调用了...");

        //1.获取jwt令牌
        String token=request.getHeader("admin-token");

        if(StringUtils.isEmpty(token)){
            log.info("服务器调用不需要admin-token");
            return true;
        }
        //3.获取载荷数据
        //后面业务可能会使用载荷数据,绑定载荷数据到当前线程
        JWT jwt = JWT.of(token);
        Admin admin=new Admin();
        admin.setId(((Integer)jwt.getPayload("id")).longValue());
        admin.setUsername((String) jwt.getPayload("username"));
        admin.setImageUrl((String) jwt.getPayload("imageUrl"));
        admin.setEmail((String) jwt.getPayload("email"));
        admin.setPhone((String) jwt.getPayload("phone"));
        admin.setName((String) jwt.getPayload("name"));
        System.out.println(admin);
        AdminThreadLocal.setAdmin(admin);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        AdminThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
